package io.renren.framework.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.framework.filter.CharacterEncodingFilter;
import io.renren.framework.interceptor.AuthorizationInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Component
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	private transient static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfig.class);
	@Autowired
	private MappingJackson2HttpMessageConverter httpMessageConverter;
	@Autowired
	private AuthorizationInterceptor authorizationInterceptor;

	@Bean
	public FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean() {
		FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean = new FilterRegistrationBean<>();
		filterRegistrationBean.setFilter(new CharacterEncodingFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.setName("characterEncodingFilter11");
		return filterRegistrationBean;
	}

	@Override
	public void addFormatters(FormatterRegistry registry) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		format.setLenient(true);
		httpMessageConverter.getObjectMapper().setDateFormat(format);
		httpMessageConverter.setObjectMapper(new CustomObjectMapper());
		DateFormatter dateFormatter = new DateFormatter();
		dateFormatter.setPattern("yyyy-MM-dd HH:mm:ss");
		dateFormatter.setLenient(true);
		registry.addFormatter(dateFormatter);

		DateFormatter dateFormatter1 = new DateFormatter();
		dateFormatter1.setPattern("yyyy-MM-dd");
		dateFormatter1.setLenient(true);
		registry.addFormatter(dateFormatter1);
		System.out.println(httpMessageConverter.getObjectMapper().getSerializationConfig().getSerializationInclusion());
	}


	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		CustomerFastJsonHttpMessageConverter fastConverter = new CustomerFastJsonHttpMessageConverter();
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
		fastConverter.setFastJsonConfig(fastJsonConfig);
		converters.add(fastConverter);
		//converters.add(1, fastConverter); 统一处理时间转换问题  暂时不处理  统一long型
	}

	/*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*","http://localhost:9529")
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "token")
            .maxAge(3600);


    }*/

	public static class CustomerFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
		@Override
		protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
				throws IOException, HttpMessageNotWritableException {
			JSON.writeJSONString(outputMessage.getBody(), obj, SerializerFeature.WriteDateUseDateFormat);
		}
	}

	public class CustomObjectMapper extends ObjectMapper {
		private static final long serialVersionUID = 3072523733092288622L;

		public CustomObjectMapper() {
			super.setSerializationInclusion(Include.ALWAYS);
		}
	}

	@Override
    public void addInterceptors(InterceptorRegistry registry) {
		List<String> excludePathPatterns = new ArrayList<String>();
		excludePathPatterns.add("*.html");
		excludePathPatterns.add("*.css");
		excludePathPatterns.add("*.js");
        registry.addInterceptor(authorizationInterceptor).excludePathPatterns(excludePathPatterns);
    }

	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
        // 放行swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
